package com.fable.ntzw_ga.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fable.common.eunm.AppHttpCodeEnum;
import com.fable.common.utils.JwtUtils;
import com.fable.common.utils.RedisUtil;
import com.fable.common.vo.ResultVO;
import com.fable.ntzw_ga.entity.SysRole;
import com.fable.ntzw_ga.entity.SysUser;
import com.fable.ntzw_ga.mapper.SysUserMapper;
import com.fable.ntzw_ga.service.ISysRoleService;
import com.fable.ntzw_ga.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Created by gzh 2023-02-19 23:49:21
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Value("${jwt.expiration}")
    private long expire;

    @Autowired
    ISysRoleService sysRoleService;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser getByUsername(String username) {
        return getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername,username));
    }

    @Override
    public String getUserAuthorityInfo(Long userId) {
        //  ROLE_admin,ROLE_normal,sys:user:list,....
        String authority = "";
        // 获取角色编码
        List<SysRole> roles = sysRoleService.list(new LambdaQueryWrapper<SysRole>()
                .inSql(SysRole::getId, "select role_id from sys_user_role where user_id = " + userId));
        if (roles.size() > 0) {
            String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
            authority = roleCodes.concat(",");
        }
        return authority;
    }



    @Override
    public ResultVO login(SysUser feastUser) {
        //1.登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(feastUser.getUsername());
        if (null == userDetails || !passwordEncoder.matches(feastUser.getPassword(), userDetails.getPassword())) {
            return ResultVO.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }else if (!userDetails.isEnabled()) {
            return ResultVO.errorResult(AppHttpCodeEnum.BAN_USER);
        }else {
            //设置security全局登录对象
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //生成token
            String token = jwtUtils.generateToken(userDetails.getUsername());
//            redisUtil.set(userDetails.getUsername(),token, 36000);
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            tokenMap.put("userName", userDetails.getUsername());
            return ResultVO.okResult(tokenMap);
        }
    }

}
